package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.CommentService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存对动态的操作(点赞,评论,喜欢)
     *
     * @param comment 评论对象
     * @return 操作之后的数目
     */
    @Override
    public Integer saveComment(Comment comment) {
        //查询所点赞动态的发布人
        Movement movement = mongoTemplate.findById(comment.getPublishId(), Movement.class);
        if (movement != null) {
            //设置点赞的动态的发布人
            comment.setPublishUserId(movement.getUserId());
        }
        //保存评论表中
        mongoTemplate.save(comment);
        //对动态表中的点赞数,评论数,喜欢数进行修改
        int count = 0;
        if (movement != null) {
            if (comment.getCommentType() == 1) {
                movement.setLikeCount(movement.getLikeCount() + 1);
                count = movement.getLikeCount();
            } else if (comment.getCommentType() == 2) {
                movement.setCommentCount(movement.getCommentCount() + 1);
                count = movement.getCommentCount();
            } else if (comment.getCommentType() == 3) {
                movement.setLoveCount(movement.getLoveCount() + 1);
                count = movement.getLoveCount();
            }
            //将修改后的数据保存到movement表中
            mongoTemplate.save(movement);
        }
        return count;
    }

    /**
     * 删除对动态的操作
     *
     * @param comment 评论对象
     * @return 操作数
     */
    @Override
    public Integer deleteComment(Comment comment) {
        //查询动态信息
        Movement movement = mongoTemplate.findById(comment.getPublishId(), Movement.class);

        Query query = new Query(
                Criteria.where("userId").is(comment.getUserId())
                        .and("publishId").is(comment.getPublishId())
                        .and("commentType").is(comment.getCommentType())
        );
        //删除动态操作数据
        mongoTemplate.remove(query, Comment.class);

        //修改动态点赞数据
        int count = 0;
        if (movement != null) {
            if (comment.getCommentType() == 1) {
                movement.setLikeCount(movement.getLikeCount() - 1);
                count = movement.getLikeCount();
            } else if (comment.getCommentType() == 2) {
                movement.setCommentCount(movement.getCommentCount() - 1);
                count = movement.getCommentCount();
            } else if (comment.getCommentType() == 3) {
                movement.setLoveCount(movement.getLoveCount() - 1);
                count = movement.getLoveCount();
            }
            mongoTemplate.save(movement);
        }
        return count;
    }

    /**
     * 查询动态评论列表
     *
     * @param page       页码
     * @param pageSize   每页条数
     * @param movementId 动态id
     * @return pageBeanVo对象
     */
    @Override
    public PageBeanVo findCommentList(Integer page, Integer pageSize, String movementId) {

        int startIndex = (page - 1) * pageSize;
        //构建查询条件
        //publishId = movementId
        //commentType = 2 -----是评论时才查询
        //需要将movementId转换为ObjectId类型,否则查询不到
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(2))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(startIndex).limit(pageSize);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);

        long count = mongoTemplate.count(query, Comment.class);
        return new PageBeanVo(page, pageSize, count, commentList);
    }

    /**
     * 保存视频点赞、评论
     *
     * @param comment 点赞、评论记录
     */
    @Override
    public void saveVideo(Comment comment) {
        Video video = mongoTemplate.findById(comment.getPublishId(), Video.class);
        comment.setPublishUserId(video.getUserId());//被操作对象所属人
        comment.setCreated(System.currentTimeMillis());//保存时间
        mongoTemplate.save(comment);
        if (ConstantUtil.VIDEO_LIKE_4.equals(comment.getCommentType())) {
            //添加喜欢数
            video.setLikeCount(video.getLikeCount() + 1);
        } else if (ConstantUtil.VIDEO_COMMENT_5.equals(comment.getCommentType())) {
            //添加评论数
            video.setCommentCount(video.getCommentCount() + 1);
        }
        mongoTemplate.save(video);
    }

    /**
     * 取消视频点赞、评论
     *
     * @param comment 取消点赞、评论记录
     */
    @Override
    public void removeVideo(Comment comment) {
        Video video = mongoTemplate.findById(comment.getPublishId(), Video.class);
        if (video != null) {
            Query query = new Query(
                    Criteria.where("publishId").is(comment.getPublishId())
                            .and("userId").is(comment.getUserId())
                            .and("commentType").is(comment.getCommentType())
            );
            mongoTemplate.remove(query, Comment.class);

            if (ConstantUtil.VIDEO_LIKE_4.equals(comment.getCommentType())) {
                //减少喜欢数
                video.setLikeCount(video.getLikeCount() - 1);
            } else if (ConstantUtil.VIDEO_COMMENT_5.equals(comment.getCommentType())) {
                //减少评论数
                video.setCommentCount(video.getCommentCount() - 1);
            }
            mongoTemplate.save(video);
        }
    }

    /**
     * 查询视频评论列表
     *
     * @param page       页码
     * @param pageSize   每页条数
     * @param movementId 动态id
     * @return pageBeanVo对象
     */
    @Override
    public PageBeanVo findVideoCommentList(Integer page, Integer pageSize, String movementId) {
        int startIndex = (page - 1) * pageSize;
        Query query = new Query(Criteria.where("publishId").is(new ObjectId(movementId))
                .and("commentType").is(5))
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(startIndex).limit(pageSize);
        List<Comment> commentList = mongoTemplate.find(query, Comment.class);

        long count = mongoTemplate.count(query, Comment.class);
        return new PageBeanVo(page, pageSize, count, commentList);
    }

    /**
     * 保存视频评论点赞
     *
     * @param comment
     */
    @Override
    public void saveCommentLike(Comment comment) {
        //根据评论id查询评论详情
        Comment returnComment = mongoTemplate.findById(comment.getPublishId(), Comment.class);
        //保存comment
        comment.setIsParent(true);
        comment.setParentId(returnComment.getId());
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishUserId(returnComment.getUserId());
        mongoTemplate.save(comment);
        //评论点赞数+1
        returnComment.setLikeCount(returnComment.getLikeCount() + 1);
        //更新信息
        mongoTemplate.save(returnComment);
    }

    /**
     * 视频评论取消点赞
     *
     * @param comment 取消点赞、评论记录
     */
    @Override
    public void removeCommentLike(Comment comment) {
        Comment returnComment = mongoTemplate.findById(comment.getPublishId(), Comment.class);
        comment.setParentId(returnComment.getId());
        Query query = new Query(
                Criteria.where("parentId").is(comment.getParentId())
                        .and("userId").is(comment.getUserId())
                        .and("commentType").is(comment.getCommentType())
        );
        mongoTemplate.remove(query, Comment.class);
        //评论点赞数-1
        returnComment.setLikeCount(returnComment.getLikeCount() - 1);
        //更新信息
        mongoTemplate.save(returnComment);
    }


    /**
     * 动态评论点赞
     * @param comment
     * @return
     */
    @Override
    public Integer saveLikeMovementComment(Comment comment) {

        //根据动态id查询动态详情
        ObjectId publishId = comment.getPublishId();
        Comment dongTai = mongoTemplate.findById(publishId, Comment.class);
        //设置点赞数
        dongTai.setLikeCount(dongTai.getLikeCount() + 1);
        //设置 打开父节点
        dongTai.setIsParent(true);

        //保存动态详情(保存父节点)
        mongoTemplate.save(dongTai);

        //设置父节点Id
        comment.setParentId(comment.getParentId());
        //设置创建时间
        comment.setCreated(System.currentTimeMillis());
        //设置点赞者id
        comment.setPublishUserId(dongTai.getUserId());
        //设置点赞数
        comment.setLikeCount(dongTai.getLikeCount());
        //设置操作类型 （6）
        comment.setCommentType(ConstantUtil.COMMENT_LIKE_6);
        //构建query
        Query query = new Query(
                Criteria.where("id").is(dongTai.getId())
        );
        //构建Update
        Update update = new Update();
        //存储到子节点上 addtoset
        update.addToSet("comment", comment);
        //存储到mongo中
        mongoTemplate.upsert(query, update, Comment.class);
        //返回点赞数
        return comment.getLikeCount();


    }


    /**
     * 动态评论取消点赞
     * @param publishId
     * @return
     */
    @Override
    public Integer disLikeMovementComment(String publishId) {
        //先根据动态Id 查询到动态评论详情
        Comment dongTai = mongoTemplate.findById(publishId, Comment.class);
        //设置点赞数
        dongTai.setLikeCount(dongTai.getLikeCount() - 1);
        //设置 关闭父节点
        dongTai.setIsParent(false);

        //保存动态详情(保存父节点)
        mongoTemplate.save(dongTai);

        return dongTai.getLikeCount();
    }
}
